﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agile.Engine.View;
using System.Collections;
using Agile.Engine;
using Agile.Engine.Data;
using System.Data;

namespace Fis.Win.Rules
{
    public class RightsInfoViewProvider : ClientViewProvider
    {
        public override Hashtable InitializeViewModel(Hashtable args)
        {
            var model = args ?? new Hashtable();

            var schema = "assembly://Agile.Engine.Config/Agile.Engine.Config.Schema/Rights.xml";

            var stream = Agile.Engine.Utils.IOUtils.InputStream(schema);

            DataTable data = new DataTable();
            data.ReadXml(stream);

            foreach (DataColumn c in data.Columns)
                c.ColumnName = c.Caption;

            //修改，取权限表数值合并

            var info = new DataAccess() { Context = DataContext, TableName = DataTableName }.Query("FUSERID='" + model["userid"].ToString() + "'");
            data.PrimaryKey = new DataColumn[] { data.Columns["FMID"] };
            foreach (var d in info.AsEnumerable())
            {
                var source = data.Rows.Find(d["FMID"]);
                source.ItemArray = d.ItemArray;
            }

            model["viewData"] = data.Select(" FGROUP=0 ").CopyToDataTable();

            return model;
        }

        public override bool ExecuteUpdate(Hashtable viewModel)
        {
            var param = Fis.Win.Utils.AppSession.CreateServiceParamter(viewModel);
            param["viewData"] = Agile.Engine.Utils.ZipUtils.ZipDataTable(viewModel["viewData"] as DataTable);

            var exec = InvokeService(param);

            if (exec)
            {
                var data = Agile.Engine.Utils.ZipUtils.UnZipDataTable(ServiceProcess.Result["viewData"].ToString());

                data.TableName = DataTableName;
                DataContext.DefaultModel.Delete(DataTableName, string.Format("FUSERID='{0}'", param["userid"]));
                DataContext.DefaultModel.UpdateTable(data);
            }
            View.Message = ServiceProcess.Message;
            return exec;
        }


    }
}
